package com.hnblc.blcwms.rest.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.hnblc.blcwms.common.constant.StringPool;
import com.hnblc.blcwms.common.exceptions.ErrorDescription;
import com.hnblc.blcwms.common.exceptions.GeneralException;
import com.hnblc.blcwms.common.interaction.Response;
import com.hnblc.blcwms.common.interaction.RestResponse;
import com.hnblc.blcwms.common.utils.encrypt.BASE64;
import com.hnblc.blcwms.persistent.interfaces.business.entity.ExpLog;
import com.hnblc.blcwms.persistent.interfaces.business.service.IExpLogService;
import com.hnblc.blcwms.persistent.interfaces.client.dto.CurrentClient;
import com.hnblc.blcwms.persistent.interfaces.client.entity.ClientAuth;
import com.hnblc.blcwms.persistent.interfaces.message.entity.MessageLog;
import com.hnblc.blcwms.rest.dto.restInteraction.EncryptRequest;
import com.hnblc.blcwms.rest.service.IMessageService;
import com.hnblc.blcwms.serviceapi.api.dto.WareHouseOperate;
import com.hnblc.blcwms.serviceapi.api.dto.untread.UntreadBody;
import com.hnblc.blcwms.serviceapi.api.dto.untread.UntreadHead;
import com.hnblc.blcwms.serviceapi.api.enums.code.ExpLogTypeEnum;
import com.hnblc.blcwms.serviceapi.api.group.custom.express.UntreadGroup;
import com.hnblc.blcwms.serviceapi.api.service.IUntreadAPIService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

/**
 * <p>Description: </p> <br/>
 *
 * @author linsong <br>
 * @version 1.0 2020.01.20 11:42 <br>
 */
@Setter
@Getter
@Api(value="订单退货API",description = "线上订单、门店配送等交易方式的退货入库通知单相关操作",tags={"客户退货（返配）通知接口"})
@RestController
@RequestMapping(value = "blc/wms/api/order")
@Validated
public class OrderReturnRestAPI extends BaseRestAPI{


    @Autowired
    IMessageService messageService;

    @Autowired
    IUntreadAPIService untreadAPIService;

    @Autowired
    IExpLogService expLogService;

    @ApiOperation(value="接收通用退货单", notes="接收线上以及门店的退货入库申请单",position = 5)
    @RequestMapping(value = "/return" ,method = RequestMethod.POST)
    @ResponseBody
    public RestResponse<List<UntreadBody>> UntreadExpress(@Validated({UntreadGroup.class})@RequestBody EncryptRequest message, HttpServletRequest request) throws IOException {
        //测试打印原始报文
        String jsonString = IOUtils.toString(request.getInputStream(), Charset.defaultCharset());
        logger.debug("***********************************untread test start***************************\n"+jsonString+"\n*********************end*************************");

        //解析业务数据 从BASE64字符串解析为JSON字符串，再解析为业务对象
        WareHouseOperate<UntreadHead> businessData;
        try {
            businessData = objectMapper.readValue(new String(BASE64.decryptBASE64(message.getBusinessData()), StringPool.CHARSET_UTF8),new TypeReference<WareHouseOperate<UntreadHead>>() { });
        }catch (Exception e){
            return new RestResponse<>(new GeneralException(ErrorDescription.ERROR_REQUEST_BAD_PARAMETER_FORMAT_0,e));
        }


        //简单验证
        this.validate(businessData, UntreadGroup.class);
        //验证客户端权限
        ClientAuth clientAuth = this.buildAuth(message,businessData);
        CurrentClient currentClient = this.clientInfoService.loadCurrentClient(clientAuth);
        if (null == currentClient || currentClient.getClientAuthInfo().size()<1) {
            return new RestResponse<>(new GeneralException(ErrorDescription.ERROR_REQUEST_CLIENT_UNAUTHORIZED_0));
        }

        try {
            if (!this.signatureValidate(message,currentClient)){
                return new RestResponse<>(new GeneralException(ErrorDescription.ERROR_REQUEST_SIGNATURE_VALIDATE_FAIL_0));
            }
        }catch (Exception e){
            logger.error("接口处理验签异常",e);
            throw new GeneralException(e);
        }

        //报文落地保存
        //取消订单操作
        MessageLog messageLog = messageService.process(currentClient, request);

        Response<UntreadBody> response = untreadAPIService.createReturnNote(businessData.getOperateDetails(),clientAuth);
        //保存创建日志，如果没有则无法反馈发货状态
        ExpLog expLog = new ExpLog(ExpLogTypeEnum.UNTREAD.code(),message.getClientId(),messageLog.getSeqNo(),businessData.getOperateDetails().getReturnErpNo(),response);
        if(!expLogService.save(expLog)){
            logger.error("Error occurred when save [UNTREAD] creation log to database");
        }
        //更新处理状态
        messageService.processed(messageLog);
        return new RestResponse(response);
    }
}
